package com.leiqichao.backend.controller;

import com.leiqichao.backend.common.Page;
import com.leiqichao.backend.common.Result;
import com.leiqichao.backend.entity.Article;
import com.leiqichao.backend.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/articles")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    // 获取所有文章
    @GetMapping
    public Result<List<Article>> getAllArticles() {
        List<Article> articles = articleService.getAllArticles();
        return Result.success(articles);
    }

    // 获取所有文章 分页
    @PostMapping("/page")
    public Result<Page<Article>> getAllArticles(@RequestBody(required = false) Page<Article> article      // 文章查询条件（可选）
    ) {

        return Result.success(articleService.page(article.getPageNum(),article.getPageSize(),article.getQueryParam()));
    }

    //发布 or 归档
    @PutMapping("/{id}/{status}")
    public Result<Boolean> updateArticleStatus(@PathVariable Long id, @PathVariable String status) {
        boolean isSuccess = articleService.updateArticleStatus(id, status);
        if (isSuccess) {
            return Result.success(true);
        } else {
            return Result.serverError();
        }
    }

    // 根据ID获取文章
    @GetMapping("/{id}")
    public Result<Article> getArticleById(@PathVariable Long id) {
        Article article = articleService.getArticleById(id);
        if (article != null) {
            return Result.success(article);
        } else {
            return Result.notFound();
        }
    }

    // 创建文章
    @PostMapping
    public Result<Boolean> createArticle(@RequestBody Article article) {
        boolean isSuccess = articleService.createArticle(article);
        if (isSuccess) {
            return Result.success(true);
        } else {
            return Result.serverError();
        }
    }

    // 更新文章
    @PutMapping("/{id}")
    public Result<Boolean> updateArticle(@PathVariable Long id, @RequestBody Article article) {
        article.setId(id);
        boolean isSuccess = articleService.updateArticle(article);
        if (isSuccess) {
            return Result.success(true);
        } else {
            return Result.serverError();
        }
    }

    // 删除文章
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteArticle(@PathVariable Long id) {
        boolean isSuccess = articleService.deleteArticle(id);
        if (isSuccess) {
            return Result.success(true);
        } else {
            return Result.serverError();
        }
    }



    //发布文章
    @PostMapping("/push/{id}")
    public Result<Boolean> pushArticle(@PathVariable Long id) {
        boolean isSuccess = articleService.pushArticle(id);
        if (isSuccess) {
            return Result.success(true);
        } else {
            return Result.serverError();
        }
    }
}